package tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class TcpPoolServlet {
    private ServerSocket severSocket = null;

    public TcpPoolServlet(int port) throws IOException {
        this.severSocket = new ServerSocket(port);
    }

    private void processConnection(Socket clientSocket){
        System.out.printf("[%s:%d] 连接\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))){
            while (true) {
                String request = bufferedReader.readLine();
                String response = process(request);
                bufferedWriter.write(response+"\n");
                bufferedWriter.flush();
                System.out.printf("[%s:%d] req: %s; resp: %s;\n",clientSocket.getInetAddress().toString(),clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
//            e.printStackTrace();
            System.out.printf("[%s:%d]:下线\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        }
    }

    private String process(String request) {
        return request;
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        Executor executor = Executors.newCachedThreadPool();
        while(true){
            Socket clientSocket = severSocket.accept();
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }

    public static void main(String[] args) throws IOException {
        TcpPoolServlet tcpPoolServlet = new TcpPoolServlet(9191);
        tcpPoolServlet.start();
    }
}
